﻿using Syspetro.Core.SysInterface;
using System;
using System.Threading.Tasks;

namespace Syspetro.DepRedis
{
    public class RedisCacher : ICache
    {
        readonly RedisHelper redis;
        public RedisCacher()
        {
            redis = new("ICache",1);
        }

        public T Get<T, V>(string key, V model, Func<V, T> func, TimeSpan expiry = default)
        {
            if (redis.KeyExists(key))
            {
                return redis.CacheGet<T>(key);
            }
            else
            {
                var re = func.Invoke(model);
                redis.CacheSetAsync(key, re, expiry == default ? new TimeSpan(0, 3, 0) : expiry);
                return re;
            }
        }

        public T Get<T>(string key)
        {
            return redis.CacheGet<T>(key);
        }

        public string Get(string key)
        {
            return redis.StringGet(key);
        }

        public Task<T> GetAsync<T>(string key)
        {
            return redis.CacheGetAsync<T>(key);
        }

        public async Task<T> GetAsync<T, V>(string key, V model, Func<V, T> func, TimeSpan expiry = default)
        {
            if (redis.KeyExists(key))
            {
                return await redis.CacheGetAsync<T>(key);
            }
            else
            {
                var re = await Task.FromResult(func.Invoke(model));
                await redis.CacheSetAsync(key, re, expiry == default ? new TimeSpan(0, 3, 0) : expiry);
                return re;
            }
        }

        public bool Remove(string key)
        {
            return redis.KeyDelete(key);
        }

        public bool Set(string key, string data, TimeSpan expiry = default)
        {
            return redis.StringSet(key, data, expiry == default ? new TimeSpan(0, 3, 0) : expiry);
        }
        public Task<bool> SetAsync(string key, string data, TimeSpan expiry = default)
        {
            return redis.StringSetAsync(key, data, expiry == default ? new TimeSpan(0, 3, 0) : expiry);
        }
    }
}
